//
// Created by LinorInk on 2024/3/9.
//

#include <memory.h>
#include "UART.h"
#include "dr16.h"

static uint8_t buffer[64];
static uint8_t txBuffer[64];
static uint8_t rxIndex = 0;
static uint8_t readIndex = 0;
static uint8_t isBusy = 0;       // 记录是否繁忙

void UART_Init(void) {
    HAL_UART_Receive_IT(UART_HANDLE, &buffer[rxIndex], 1);
}

/**
 * @brief 发送数据 不要在中断中调用，只在主函数中调用
 * @param data 需要发送的数据
 * @param length 数据长度
 */
void UART_Write(uint8_t*data, uint16_t length) {
    // while(i);
    memcpy(txBuffer, data, length);
    HAL_UART_Transmit_DMA(UART_HANDLE, txBuffer, length);
    isBusy = 1;
}

uint8_t UART_Read() {
    if(readIndex == rxIndex)    return 0;

    uint8_t data = buffer[readIndex];
    readIndex = (readIndex + 1) % 64;
    return data;
}

uint8_t UART_isBusy() {
    return isBusy;
}

uint8_t UART_isBufferFit(uint8_t size) {
    return (rxIndex - readIndex) > size;
}

uint8_t UART_isEmpty() {
    return readIndex == rxIndex;
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart == UART_HANDLE) {
        rxIndex = (rxIndex + 1) % 64;

        HAL_UART_Receive_IT(UART_HANDLE, &buffer[rxIndex], 1);
    }

    if (huart == &huart3) {
        DR16_Rx_Callback();
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart == UART_HANDLE) isBusy = 0;
}
